from app.extensions import db
from flask import request
from datetime import datetime
from app.models.model_mixin import BaseMixin
from flask_login import current_user


# article model
class Article(db.Model, BaseMixin):
    """params: status 9:默认 0:回收站
    audit_status: 文章审核状态：9为默认:未审核，8:退回，7:通过
    attachment: 附件
    """
    id = db.Column(db.Integer, primary_key=True)
    cid = db.Column(db.Integer, db.ForeignKey('category.id'))
    rid = db.Column(db.Integer, db.ForeignKey('report.id'))
    uid = db.Column(db.Integer, db.ForeignKey('user.id'), index=True)
    thumb = db.Column(db.String(255))
    video = db.Column(db.String(255))
    audio = db.Column(db.String(255))
    title = db.Column(db.String(255))
    content = db.Column(db.Text)
    edit_content = db.Column(db.Text)
    audit_status = db.Column(db.Integer, default=10, index=True)
    status = db.Column(db.Integer, default=9, index=True)
    sort = db.Column(db.Integer, default=0, index=True)
    url = db.Column(db.String(255))
    created_at = db.Column(db.DateTime, default=datetime.utcnow, index=True)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow)

    user = db.relationship('User', back_populates='articles')
    category = db.relationship('Category', back_populates='articles')
    report = db.relationship('Report', back_populates='articles')

    attachments = db.relationship('Attachment', back_populates='article')

    # 获取录用文章
    @classmethod
    def get_hired_count(cls):
        return cls.query.filter(cls.uid == current_user.id, cls.rid != None, cls.status == 9).count()

    # 获取未录用文章
    @classmethod
    def get_not_hired_count(cls):
        return cls.query.filter(cls.uid == current_user.id, cls.rid == None, cls.status == 9).count()

    # 获取报送积分
    @classmethod
    def get_hired_integral(cls):
        return cls.get_hired_count() * 2 + cls.get_not_hired_count() * 1 

    def to_dict(self, content=False):
        res_data = {
            'id': self.id,
            'cid': self.category.id,
            'user': {
                'name': self.user.nickname
            },
            'report':  None if self.report is None else self.report.id,
            'thumb': self.thumb,
            'title': self.title,
            'status': self.status,
            'audit_status': self.audit_status,
            'url': self.url,
            'created_at': self.created_at,
        }
        if self.attachments:
            res_data.update({
                'attachment': [item.to_dict() for item in self.attachments],
            })
        content and res_data.update({'content': self.content, 'edit_content': self.edit_content})
        if 'category' in request.args.get('expand', ''):
            res_data.update({
                'category': {
                    'id': self.category.id,
                    'title': self.category.title
                }
            })
        return res_data

    @staticmethod
    def to_collection_dict(query, page, per_page=10):
        resources = query.paginate(page, per_page, False)
        data = {
            'items': [item.to_dict() for item in resources.items],
            '_meta': {
                'hired_count': Article.get_hired_count(),
                'not_hired_count': Article.get_not_hired_count(),
                'hired_integral': Article.get_hired_integral(),
                'page': page,
                'per_page': per_page,
                'total_pages': resources.pages,
                'total_items': resources.total
            }
        }
        return data
